<?php
require_once('../lib/standard.php');
$pineza = new Globals(FALSE);
if (!session_set('admin'))
	telos('Administrator denied!');

backup_table('user', '`login`, `name`, `password`, `email`, `board`, `date`');
backup_table('board', '`user`, `color`, `title`, `date`');
backup_table('note', '`key`, `user`, `board`, `text`, `color`, ' .
	'`font`, `priority`, `size`, `date`');

$pineza->close_database();
print AJAX_SEP;

function backup_table($table, $prjlist) {
	global $pineza;
	$outfile = '../backup/' . $table;
	$fh = fopen($outfile, 'w');
	if (!$fh) telos($outfile . ': cannot open file for writing');

	$result = @mysqli_query($pineza->db, "SELECT {$prjlist } FROM `{$table}`");
	if (!$result) telos($table . ': backup failed (' . mysqli_error($pineza->db) . ')');

	while ($row = mysqli_fetch_array($result, MYSQLI_NUM)) {
		$cnt = count($row);
		$line = $row[0];
		for ($i = 1; $i < $cnt; $i++) {
			$line .= "\t" . $row[$i];
		}
		$line .= "\n";
		fwrite($fh, $line);
	}
	fclose($fh);
	chmod($outfile, 0666);
}

?>
